package com.example.elmmerchants.Sign;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.elmmerchants.Create_Shop.Set_Shop_Data;
import com.example.elmmerchants.Email.SendEmail;
import com.example.elmmerchants.First_Page_Fragment.First_Page;
import com.example.elmmerchants.SQL.Add_Merchant_SQL;
import com.example.elmmerchants.SQL.Connection_SQL;
import com.example.elmmerchants.R;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class OTP_Login_Method extends Fragment {

    View root;
    TextView get_otp_code_btn;
    EditText email, verification_code;
    Button login_with_otp;

    Context context;
    String name = "";
    String user_email = "";
    String sms = "";
    AlertDialog dialog;
    boolean is_in_db = false;
    boolean is_approved = false;
    boolean is_loading_data = false;
    boolean is_update_data = false;
    String android_id;
    String shop_status, qualification_status, legal_status, first_category, second_category;

    public OTP_Login_Method(Context context, String android_id) {
        this.context = context;
        this.android_id = android_id;
    }

    private class Loading_Data_Thread extends Thread{
        @Override
        public void run() {
            is_approved = false;
            is_in_db = false;
            is_loading_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email.getText().toString());
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        if (set.getString("email").equals(email.getText().toString())) {
                            is_in_db = true;
                            first_category = set.getString("first_category");
                            second_category = set.getString("second_category");
                            if (set.getInt("shop_information") == 1) {
                                shop_status = "已录入";
                            }
                            else {
                                shop_status = "待录入";
                            }

                            if (set.getInt("qualification_information") == 1) {
                                qualification_status = "已录入";
                            }
                            else {
                                qualification_status = "待录入";
                            }

                            if (set.getInt("legal_information") == 1) {
                                legal_status = "已录入";
                            }
                            else {
                                legal_status = "待录入";
                            }
                            if (set.getInt("approved") == 1) {
                                is_approved = true;
                            }
                        }
                    }
                    is_loading_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                while (!is_loading_data) {
                    try{
                        Thread.sleep(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (is_in_db) {
                            if (is_approved) {
                                Update_Android_ID_Go_To_First_Page_Thread updateAndroidIdGoToFirstPageThread = new Update_Android_ID_Go_To_First_Page_Thread();
                                updateAndroidIdGoToFirstPageThread.start();
                            }
                            else {
                                Update_Android_ID_Go_To_Create_Shop_Page_Thread updateAndroidIdGoToCreateShopPageThread = new Update_Android_ID_Go_To_Create_Shop_Page_Thread();
                                updateAndroidIdGoToCreateShopPageThread.start();
                            }
                        }
                        else {
                            dialog.dismiss();
                            String auto_name = create_user_name();
                            String auto_password = create_password();
                            Toast.makeText(root.getContext(), "注册成功，请在电邮查看系统自动注册的账号", Toast.LENGTH_SHORT).show();
                            new SendEmail(user_email, sms, "饿了没", "【饿了没】您已成功注册！商家账号：" + auto_name + "，密码：" + auto_password + "，该账号可用于登录商家系统，登录后请尽快修改密码。").sendemail();
                            new Add_Merchant_SQL(email.getText().toString(), auto_name, auto_password, 0, 0, 0, 0, "全部,", 0.0, "", 0, 0, "暂无", "暂无", "", "", "", "", "", android_id).add_merchant();
                            Intent intent = new Intent(context, Set_Shop_Data.class);
                            intent.putExtra("user_email", email.getText().toString());
                            intent.putExtra("first_category", "暂无");
                            intent.putExtra("second_category", "暂无");
                            intent.putExtra("shop_information_status", "待录入");
                            intent.putExtra("qualification_information_status", "待录入");
                            intent.putExtra("legal_information_status", "待录入");
                            startActivity(intent);
                            getActivity().finish();
                        }
                    }
                });
            });
        }
    }

    private class Update_Android_ID_Go_To_First_Page_Thread extends Thread {
        @Override
        public void run() {
            is_update_data = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "update `elm`.`merchant` set phone_id = ? WHERE email = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, android_id);
                    preparedStatement.setString(2, user_email);
                    preparedStatement.executeUpdate();
                    is_update_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_update_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();

                    Intent intent = new Intent(context, First_Page.class);
                    intent.putExtra("email", email.getText().toString());
                    startActivity(intent);
                    getActivity().finish();
                }
            });
        }
    }

    private class Update_Android_ID_Go_To_Create_Shop_Page_Thread extends Thread {
        @Override
        public void run() {
            is_update_data = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "update `elm`.`merchant` set phone_id = ? WHERE email = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, android_id);
                    preparedStatement.setString(2, user_email);
                    preparedStatement.executeUpdate();
                    is_update_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_update_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();

                    Intent intent = new Intent(context, Set_Shop_Data.class);
                    intent.putExtra("user_email", email.getText().toString());
                    intent.putExtra("first_category", first_category);
                    intent.putExtra("second_category", second_category);
                    intent.putExtra("shop_information_status", shop_status);
                    intent.putExtra("qualification_information_status", qualification_status);
                    intent.putExtra("legal_information_status", legal_status);
                    startActivity(intent);
                    getActivity().finish();
                }
            });
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_o_t_p__login__method, container, false);

        email = root.findViewById(R.id.email);
        verification_code = root.findViewById(R.id.verification_code);

        get_otp_code_btn = root.findViewById(R.id.get_otp_code_btn);
        get_otp_code_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println(android_id);
                if (email.getText().toString().isEmpty()) {
                    Toast.makeText(root.getContext(), "请输入电子邮件", Toast.LENGTH_SHORT).show();
                }
                else {
                    user_email = email.getText().toString();
                    sms = sms_code();
                    String text = "【饿了没】欢迎使用饿了没外卖平台，验证码 " + sms + "。如非本人操作，请检查账号安全。";
                    new SendEmail(email.getText().toString(), sms, "饿了没注册验证码", text).sendemail();
                    get_otp_code_btn.setEnabled(false);
                    get_otp_code_btn.setTextColor(Color.rgb(211, 211, 211));
                    get_otp_code_btn.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            get_otp_code_btn.setEnabled(true);
                            get_otp_code_btn.setTextColor(Color.rgb(255, 235, 59));
                        }
                    }, 60000);
                }
            }
        });

        login_with_otp = root.findViewById(R.id.login_with_otp);
        login_with_otp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (verification_code.getText().toString().isEmpty() || email.getText().toString().isEmpty()) {
                    Toast.makeText(root.getContext(), "请输入所有数据", Toast.LENGTH_SHORT).show();
                }
                else {
                    if (verification_code.getText().toString().equals(sms)) {
                        set_dialog();
                        Loading_Data_Thread loadingDataThread = new Loading_Data_Thread();
                        loadingDataThread.start();
                    }
                    else {
                        Toast.makeText(root.getContext(), "验证码错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        return root;
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(root.getContext());
        LayoutInflater inflater1 = LayoutInflater.from(root.getContext());
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }

    public String create_user_name() {
        name = "";
        int how_long = new Random().nextInt(4) + 8;

        Character[] random_text = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '_'};
        for (int i = 0; i < how_long; i++) {
            int num = new Random().nextInt(62);
            name += random_text[num];
        }

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(() -> {
            try {
                Connection_SQL user_sql = new Connection_SQL();
                Connection connection = user_sql.connection();
                String sql = "SELECT * FROM merchant WHERE user_name = ?;";
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, name);
                ResultSet set = preparedStatement.executeQuery();
                while (set.next()) {
                    if (set.getString("user_name").equals(name)) {
                        create_user_name();
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        return name;
    }

    public String create_password() {
        StringBuilder set_password = new StringBuilder();
        Character[] random_text = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'};
        for (int i = 0; i < 6; i++) {
            int num = new Random().nextInt(61);
            set_password.append(random_text[num]);
        }

        return set_password.toString();
    }

    public String sms_code() {
        String ans = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            ans += String.valueOf(random.nextInt(9));
        }
        System.out.println(ans);
        return ans;
    }
}